package com.water.wl.newwater;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.water.wl.newwater.adapter.TweetAdapter;
import com.water.wl.newwater.api.ApiClient;
import com.water.wl.newwater.bean.ListEntity;
import com.water.wl.newwater.bean.Tweet;
import com.water.wl.newwater.bean.Tweet1;
import com.water.wl.newwater.bean.TweetsList;
import com.water.wl.newwater.util.XmlUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by wds1993225 on 2016/3/10.
 */
public class TweetTab extends Fragment {

    private ListView listView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TweetAdapter tweetAdapter;
    //private ArrayList<Tweet>  arrayList = new ArrayList<Tweet>();
    private List<Tweet> arrayList = new ArrayList<Tweet>();
    private String partUrl = "action/api/tweet_list";

    private ParserTask mParserTask;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tweet_list,null);
        listView = (ListView)view.findViewById(R.id.listView);
        initHttpData();
        //initData();
        //tweetAdapter = new TweetAdapter(getActivity(),arrayList);
        tweetAdapter = new TweetAdapter(getActivity(),R.layout.tweet_list_item,arrayList);
        listView.setAdapter(tweetAdapter);

        swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeRefresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.blue,android.R.color.holo_red_light
                ,android.R.color.holo_green_dark,android.R.color.holo_orange_light);

        return view;
    }

    private void initHttpData(){
        RequestParams params = new RequestParams();
        params.put("uid", 1);
        params.put("pageIndex", 0);
        params.put("pageSize", 20);
        String url = partUrl;
        ApiClient.get(url,params,responseHandler);
    }
    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            executeParserTask(responseBody);

            Message message = new Message();
            message.what = 0;
            handler.sendMessage(message);
            Log.i("响应成功",String.valueOf(responseBody));

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            Log.i("网络问题",error.getMessage());
        }
    };
    class ParserTask extends AsyncTask<Void, Void, String> {

        private final byte[] reponseData;
        private List<Tweet> list;

        public ParserTask(byte[] data) {
            this.reponseData = data;
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                ListEntity<Tweet> data = parseList(new ByteArrayInputStream(
                        reponseData));
                list = data.getList();
                Log.i("解析成功",String.valueOf(list));

            } catch (Exception e) {
                e.printStackTrace();

            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //Log.i("数据为",String.valueOf(arrayList));

                executeOnLoadDataSuccess(list);
                //executeOnLoadFinish();
        }
    }
    private TweetsList parseList(InputStream is) throws Exception {
        TweetsList list = XmlUtils.toBean(TweetsList.class, is);
        //ArrayList<Tweet> = XmlUtils.toBean(ArrayList<Tweet>.class,is);
        return list;
    }

    private void executeOnLoadDataSuccess(List<Tweet> data) {
        arrayList = data;
        Log.i("数据为",String.valueOf(arrayList));


        tweetAdapter.addData(data);

    }
    private void executeParserTask(byte[] data) {
        mParserTask = new ParserTask(data);
        mParserTask.execute();
    }

   /* private void initData(){
        Map<String,Integer> map = new HashMap<>();
        map.put("uid",1);
        map.put("pageIndex",0);
        map.put("pageSize",20);
        JSONObject jsonObject = new JSONObject(map);
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
                ApiClient.getAbsoluteApiUrl(url),jsonObject,new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                for(int i = 0 ;i < response.length();i ++){
                    try {
                        JSONObject object = response.getJSONObject(i);
                        Tweet tweet = new Tweet();
                        tweet.setAuthor(object.getString("author"));
                        tweet.setPortrait(object.getString("portrait"));
                        arrayList.add(tweet);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
                Log.i("解析xml",String.valueOf(response));

            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("网络有问题",error.getMessage());
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);

            }
        });
        ApplicationController.getInstance().addToRequestQueue(jsonArrayRequest);

    }*/

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:swipeRefreshLayout.setRefreshing(false);
                    tweetAdapter.notifyDataSetChanged();
                    break;
                case 1:                       //TODO 这里要写一个全局异常捕获
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getActivity(),"你的鸡巴网络有问题",Toast.LENGTH_SHORT);
                    break;
                default:
                    break;
            }
        }
    };
}
